import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:ui' as ui;

import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart' as Widgets;
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:intl/intl.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/datas/home_announcement_mdoel.dart';
import 'package:flutter_syt/domain/widgets/common_dialog.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/global_common.dart';
import 'package:flutter_syt/global_easy_loading.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/starter/http/manager.dart';
import 'package:flutter_syt/utils/dio_download_img.dart';
import 'package:flutter_syt/widgets/qr_code_view.dart';
import 'package:flutter_syt/widgets/dyt_aliyun_widget.dart';
import 'package:flutter_syt/widgets/web_video_page.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';
import 'package:path_provider/path_provider.dart';

class UtilsOther {
  static Future<bool> checkShowVertification(
      {required String account,
      required BuildContext context,
      required DytAliyunStatus status}) async {
    int code = 0;
    try {
      code = await API.shared.common.sendCodeCount(
        account,
      );
    } catch (e) {
      UtilsOther.showCustomShowError(e);
      // customShowError(S().network_error);
      return false;
    }
    bool isVertifica = false;
    if (code >= 3) {
      // appContext
      // await showVertificationCodeDialog(
      //   context,
      //   vertifivationBlock: (isSuccess) {
      //     isVertifica = true;
      //   },
      // );

      await showDytAliyunDialog(
        context,
        status: DytAliyunStatus.DytAliyunStatusLogin,
        onSuccess: (isSuccess) {
          isVertifica = true;
        },
      );
      await Future.delayed(Duration(milliseconds: 100));
      return isVertifica;
    } else {
      isVertifica = true;
      return isVertifica;
    }
  }

  static Future<String> showCustomShowError(dynamic e) async {
    if (e is DioException) {
      // && !(e.error is SocketException)
      if (e.error is NetError) {
        NetError error = e.error as NetError;
        customShowToast(error.msg);
      } else if (e.error is SocketException) {
        customShowToast(S().network_error);
      }

      // if (outLoginCodes.contains("${e.response?.statusCode}") ||
      //     authFailCodes.contains("${e.response?.statusCode}")) {
      //   try {
      //     Navigator.of(appContext.context!).popUntil((route) => route.isFirst);
      //   } catch (e) {}
      // } else {
      //   customShowToast(e.error?.msg ??'');
      // }
      return e.message ?? '';
    } else {
      customShowToast(S().network_error);
      // customShowError(S().network_error);
      return S().network_error;
    }
  }

  static handleException(Exception exception) {
    if (exception is DioException) {
      switch (exception.type) {
        case DioExceptionType.connectionTimeout:
          break;
        default:
      }
    }
    // if (exception is DioError) {
//     switch (exception.type) {
//       case DioErrorType.connectTimeout:
//         {
//           customShowError('链接服务器超时');
//           // return UnknownException(error.message);
//         }
//       case DioErrorType.receiveTimeout:
//         {
//           customShowError('请求服务器超时');
//           //  UnknownException(error.message);
//         }
//       case DioErrorType.sendTimeout:
//         // return NetworkException(message: error.message);
//       case DioErrorType.cancel:
//         // return CancelException(error.message);
//       case DioErrorType.response:
//         try {
//           int? errCode = exception.response?.statusCode;
//           switch (errCode) {
//             case 400:
//               // return BadRequestException(message: "请求语法错误", code: errCode);
//             case 401:
//               // return UnauthorisedException(message: "没有权限", code: errCode);
//             case 403:
//               // return BadRequestException(message: "服务器拒绝执行", code: errCode);
//             case 404:
//               // return BadRequestException(message: "无法连接服务器", code: errCode);
//             case 405:
//               // return BadRequestException(message: "请求方法被禁止", code: errCode);
//             case 500:
//               // return BadServiceException(message: "服务器内部错误", code: errCode);
//             case 502:
//               // return BadServiceException(message: "无效的请求", code: errCode);
//             case 503:
//               // return BadServiceException(message: "服务器挂了", code: errCode);
//             case 505:
//               // return UnauthorisedException(
//                   // message: "不支持HTTP协议请求", code: errCode);
//             default:
//               // return UnknownException(error.message);
//           }
//         } on Exception catch (_) {
//           // return UnknownException(error.message);
//         }

//       // case DioErrorType.other:
//       //   if (error.error is SocketException) {
//       //     return NetworkException(message: error.message);
//       //   } else {
//       //     return UnknownException(error.message);
//       //   }
//       // default:
//       //   return UnknownException(error.message);
//     }
//   } else {
//     // return UnknownException(error.toString());
//   }
// }
  }

  static showBottomSaveImage({dynamic image, BuildContext? context}) async {
    var item = [
      S().websave,
      S().cancel,
      // S.of(context).map_tencent
    ];
    // if (Platform.isIOS) {
    //   item.add(S.of(context).map_apple);
    // }
    return showModalBottomSheet(
      shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
        topLeft: Radius.circular(8),
        topRight: Radius.circular(8),
      )),
      isScrollControlled: true,
      context: context ?? appContext.context!,
      builder: (BuildContext context) {
        return ListView.separated(
          separatorBuilder: (context, index) {
            return const Divider(
              height: 1,
              color: ThemeColor.colorBlack40,
            );
          },
          shrinkWrap: true,
          itemCount: item.length,
          itemBuilder: (BuildContext context, int index) {
            return ListTile(
              title: Center(
                child: Text(
                  item[index],
                  style: TextStyle(
                    fontSize: 14,
                    color: ThemeColor.colorBlack100,
                  ),
                ),
              ),
              onTap: () async {
                if (index == 0) {
                  // String title =
                  //     DateTime.now().millisecondsSinceEpoch.toString() + "_dyt";
                  // // DLog(title);
                  // if (image is String) {
                  //   DioDownloadImg.downAndSaveImg(
                  //     image,
                  //     title,
                  //   );
                  // } else {
                  //   if (image is Uint8List) {
                  //     DioDownloadImg.bytesAndSaveImg(image, title, context);
                  //   } else if (image is ImageProvider) {
                  //     ui.Image imageUI = await loadImageByProvider(image);
                  //     var a = await imageUI.toByteData(
                  //         format: ui.ImageByteFormat.png);
                  //     if (a != null) {
                  //       DioDownloadImg.bytesAndSaveImg(
                  //           a.buffer.asUint8List(), title, context);
                  //     }
                  //   } else if (image is File) {
                  //     DioDownloadImg.fileAndSaveImg(image, title, context);
                  //   }
                  // }
                  saveImageToAlbum(image);
                }
                Navigator.pop(context);
              },
            );
          },
        );
      },
    );
  }

  static Future saveImageToAlbum(var image) async {
    String title =
        DateTime.now().millisecondsSinceEpoch.toString() + "_dyt";
    // DLog(title);
    if (image is String) {
      DioDownloadImg.downAndSaveImg(
        image,
        title,
      );
    } else {
      if (image is Uint8List) {
        DioDownloadImg.bytesAndSaveImg(image, title,appContext.context!);
      } else if (image is ImageProvider) {
        ui.Image imageUI = await loadImageByProvider(image);
        var a = await imageUI.toByteData(
            format: ui.ImageByteFormat.png);
        if (a != null) {
          DioDownloadImg.bytesAndSaveImg(
              a.buffer.asUint8List(), title,appContext.context!);
        }
      } else if (image is File) {
        DioDownloadImg.fileAndSaveImg(image, title, appContext.context!);
      }
    }
  }

  static OverlayEntry? _popupEntry;

  static showOverlay(BuildContext context, Offset offset, dynamic image) {
    DLog('dalksjdlks   ${offset}');
    _popupEntry = OverlayEntry(
        builder: (context) => Stack(
              children: [
                Positioned.fill(child: GestureDetector(
                  onTap: () {
                    _popupEntry?.remove();
                    _popupEntry = null;
                  },
                  behavior: HitTestBehavior.opaque,
                )),
                Positioned(
                  left: offset.dx,
                  top: offset.dy,
                  child: Material(
                      color: Colors.transparent,
                      child: GestureDetector(
                        onTap: ()async {
                          String title =
                              DateTime.now().millisecondsSinceEpoch.toString() + "_dyt";
                          // DLog(title);
                          if (image is String) {
                            DioDownloadImg.downAndSaveImg(image, title);
                          } else {
                            if (image is Uint8List) {
                              DioDownloadImg.bytesAndSaveImg(image, title, context);
                            } else if (image is ImageProvider) {
                              ui.Image imageUI = await loadImageByProvider(image);
                              var a = await imageUI.toByteData(
                                  format: ui.ImageByteFormat.png);
                              if (a != null) {
                                DioDownloadImg.bytesAndSaveImg(
                                    a.buffer.asUint8List(), title, context);
                              }
                            } else if (image is File) {
                              DioDownloadImg.fileAndSaveImg(image, title, context);
                            }
                          }
                        },
                        child: Container(
                          color: Colors.white,
                          width: 80,
                          height: 40,
                          alignment: Alignment.center,
                          child: Text(S.current.websave),
                        ),
                      )
                    // child: Column(
                    //   children: [
                    // ListTile(
                    //   title: Text('保存'),
                    //   onTap: () {
                    //     _popupEntry?.remove();
                    //     _popupEntry = null;
                    //     // 处理保存逻辑
                    //     // entry.remove();
                    //     // entry.remove();
                    //   },
                    // ),
                    // ListTile(
                    //   title: Text('取消'),
                    //   onTap: () {
                    //     _popupEntry?.remove();
                    //   },
                    // ),
                    //   ],
                    // ),
                  ),
                ),
              ],
            ));

    Overlay.of(context).insert(_popupEntry!);
  }

  static Future showPopupMeun(
      Offset offset, dynamic image, BuildContext context) async {
    await showMenu(
      context: context,
      position: RelativeRect.fromLTRB(
          offset.dx, offset.dy, 1.sw - offset.dx - 100, 0),
      items: [
        PopupMenuItem(
          child: Text(S.current.websave),
          value: 1,
        ),
        // PopupMenuItem(
        //   child: Text(S.current.webclose),
        //   value: 3,
        // ),
      ],
    ).then((value) async {
      if (value == 1) {
        String title =
            DateTime.now().millisecondsSinceEpoch.toString() + "_dyt";
        // DLog(title);
        if (image is String) {
          DioDownloadImg.downAndSaveImg(image, title);
        } else {
          if (image is Uint8List) {
            DioDownloadImg.bytesAndSaveImg(image, title, context);
          } else if (image is ImageProvider) {
            ui.Image imageUI = await loadImageByProvider(image);
            var a = await imageUI.toByteData(format: ui.ImageByteFormat.png);
            if (a != null) {
              DioDownloadImg.bytesAndSaveImg(
                  a.buffer.asUint8List(), title, context);
            }
          } else if (image is File) {
            DioDownloadImg.fileAndSaveImg(image, title, context);
          }
        }
      }
      // DLog(value);
    });
  }

  static Future<ui.Image> loadImageByProvider(
    ImageProvider provider, {
    ImageConfiguration config = ImageConfiguration.empty,
  }) async {
    Completer<ui.Image> completer = Completer<ui.Image>(); //完成的回调
    ImageStreamListener? listener;
    ImageStream stream = provider.resolve(config); //获取图片流
    listener = ImageStreamListener((ImageInfo frame, bool sync) {
//监听
      final ui.Image image = frame.image;
      completer.complete(image); //完成
      if (listener != null) {
        stream.removeListener(listener); //移除监听
      }
    });
    stream.addListener(listener); //添加监听
    return completer.future; //返回
  }

  // HomeAnnouncementsPageState
  static clickAnnouncementJump(
      HomeAnnouncementMdoel item, BuildContext context) {
    if (item.type == 3) {
      var web = WebVideoPage(item.newsUrl ?? '');
      Navigator.of(context).push(MaterialPageRoute(
          builder: (context) => web,
          settings: RouteSettings(name: "web_in_view", arguments: "")));
    } else if (item.type == 1) {
      var storyLocal = appContext.storage.getString("storyLocal");
      var url = GlobalData.noticedetail(context, item.id ?? 0);
      if (storyLocal != null) {
        url = url +
            (url.contains('?') ? "&lang=$storyLocal" : "?lang=$storyLocal");
      } else {
        var local = Intl.getCurrentLocale();
        url = url + (url.contains('?') ? "&lang=$local" : "?lang=$local");
      }
      var web = WebVideoPage(url);
      Navigator.of(context).push(MaterialPageRoute(
          builder: (context) => web,
          settings: RouteSettings(name: "web_in_view", arguments: "")));
      // Navigator.of(context).push(MaterialPageRoute(
      //     builder: (ctx) => WebProtocolDetailPage(
      //         GlobalData.noticedetail(context, item.id ?? 0))));
    } else if (item.type == 2) {
      RouteManager.push(context,
          RoutMapping.gameDetail((item.id ?? 0).toString(), isVideo: false));
    }
  }

  static Size boundingTextSize(String text, TextStyle style,
      {int maxLines = 2 ^ 31, double maxWidth = double.infinity}) {
    if (text.isEmpty) {
      return Size.zero;
    }
    final TextPainter textPainter = TextPainter(
        textDirection: Widgets.TextDirection.ltr,
        text: TextSpan(text: text, style: style),
        maxLines: maxLines)
      ..layout(maxWidth: maxWidth);
    return textPainter.size;
  }

  static DateTime lastDayOfMonth() {
    return DateTime.utc(2023, 8, 8);
    // final date = month.month < 12
    //     ? DateTime.utc(month.year, month.month + 1, 1)
    //     : DateTime.utc(month.year + 1, 1, 1);
    // return date.subtract(const Duration(days: 1));
  }

  static DateTime firstDayOfMonth() {
    return DateTime.utc(2023, 7, 27);
    // return DateTime.utc(month.year, month.month, 1);
  }

  static DateTime getShowDate() {
    DateTime newDate = DateTime.now();
    DateTime beginDate = firstDayOfMonth();
    DateTime endDate = lastDayOfMonth();
    if (beginDate.difference(newDate).inDays > 0) {
      return beginDate;
    } else if (newDate.difference(endDate).inDays >= 0) {
      return endDate;
    } else {
      return newDate;
    }
  }

  static List qrWhiteList = [];

  static scanVenue(BuildContext context) async {
    Future getQRWhiteList() async {
      var list = await API.shared.common.qrWhiteListV2();
      qrWhiteList = list;
    }

    var result = await Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => QRCodePage(),
      ),
    );
    if (result is String) {
      var isContain = false;
      if (qrWhiteList.isEmpty) {
        await getQRWhiteList();
      }

      Uri uri = Uri.parse(result);
      var sha = sha256.convert(utf8.encode(uri.host)).toString();

      for (var url in qrWhiteList) {
        if (sha == url) {
          isContain = true;
          break;
        }
      }
      if (isContain) {
        RouteManager.push(context, RoutMapping.webDetail(result));
      } else {
        customShowToast(S.of(context).Unrecognized_content);
      }
    }
  }

  static Future<void> downloadPdfToAppFiles(String url, String fileName) async {
    try {
      Permission.manageExternalStorage.request();
      Permission.storage.request();
      // 获取应用的Documents目录
      final directory = await getApplicationDocumentsDirectory();
      final filePath = '${directory.path}/$fileName';

      // 使用Dio下载文件
      final response = await Dio().get(
        url,
        options: Options(
          responseType: ResponseType.bytes,
          followRedirects: false,
          receiveTimeout: const Duration(seconds: 30),
        ),
      );

      // 将文件写入本地
      final file = File(filePath);
      await file.writeAsBytes(response.data);

      // 提示用户下载成功
      customShowToast('PDF文件已保存到应用文件');
    } catch (e) {
      // 处理错误
      await showCustomShowError(e);
    }
  }
}
